import React, { useState, useRef, useEffect } from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import './index.less';
/*
 * 1.首先计算包裹层的宽度，既是轮播图每个块的宽度
 * 2.根据轮播块的数量计算总宽度
 * 3.根据点击计算要滚动的距离
 *
 *
 * React.Children.toArray,用法：把孩子专户为数组，数组返回数组，一个元素修改为一个元素的数组
 * React.Children.map 也一样。
 * */
interface carouselPropsType {
  afterChange?: () => void;
}
const carousel: React.FC<carouselPropsType> = props => {
  const { children } = props;
  const carouselDomRef = useRef(document.createElement('div'));
  const [current, setCurrent] = useState(0);
  const [itemWith, setItemWith] = useState(0);
  const [childrenCount, setChildrenCount] = useState(0);

  const onClickCheck = (index: number) => {
    setCurrent(index);
  };

  useEffect(() => {
    setItemWith(carouselDomRef?.current?.offsetWidth);
    setChildrenCount(React.Children.count(children));
  }, []);

  return (
    <div className="ant-carousel" ref={carouselDomRef}>
      <div className="slick-slider slick-initialized" dir="ltr">
        {/* 轮播图*/}
        <div className="slick-list">
          <div
            className="slick-track"
            // 这些要计算的
            style={{
              width: childrenCount * itemWith || 100000,
              opacity: 1,
              transform: `translate3d(${-itemWith * current}px, 0px, 0px)`,
            }}
          >
            {React.Children.map(children, (item, index) => {
              return (
                <div
                  // data-index="0"
                  className={classNames('slick-slide', {
                    'slick-active slick-current': index === current,
                  })}
                  // tabIndex="-1"
                  // aria-hidden="false"
                  style={{ outline: 'none', width: 388 }}
                >
                  <div
                    // tabIndex="-1"
                    style={{
                      width: '100%',
                      display: 'inline-block',
                      outline: 'none',
                    }}
                  >
                    {item}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        {/*  按钮 */}
        <ul className="slick-dots slick-dots-bottom">
          {React.Children.map(children, (item, index) => {
            return (
              <li className={classNames({ 'slick-active': current === index })}>
                <button
                  onClick={() => {
                    onClickCheck(index);
                  }}
                >
                  {index}
                </button>
              </li>
            );
          })}
        </ul>
      </div>
    </div>
  );
};

export default carousel;
